/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description: 群聊服务
 */
import 'package:chat_client/models/group_model.dart';
import 'package:chat_client/repositories/group_repository.dart';
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';

class GroupService {
  // 单例模式
  GroupService._internal();
  static final GroupService _instance = GroupService._internal();
  static GroupService get instance => _instance;

  final ApiService apiService = ApiService.instance;
  final GroupRepository _groupRepository = GroupRepository.instance;

  //  储存群聊信息
  Future<String> storeGroup(Map<String, dynamic> json) async {
    final Group group = Group.fromJson(json);
    final List<Member> memberList = (json['members'] as List)
        .map((m) => Member.fromJson(m, group.groupId))
        .toList();

    await _groupRepository.setGroup(group);

    await _groupRepository.setGroupMembers(memberList, group.groupId);
    return group.groupId;
  }

  // 创建房间
  Future<Group?> createGroup({
    required List contactIds,
    required String groupName,
  }) async {
    final response = await apiService.post('/group/create', {
      'contactIds': contactIds,
      'groupName': groupName,
    });
    final groupId = await storeGroup(response['data']);
    return getLocalGroupById(groupId);
  }

  // 获取加入的群聊列表
  Future<void> getRometeGroupList() async {
    final response = await apiService.get('/group/list');
    final List list = response['data'];
    if (list.isEmpty) return;
    for (var g in list) {
      await storeGroup(g);
    }
  }

  // 根据房间 ID 获取房间详情
  Future<void> getRemoteGroupById(String groupId) async {
    final response =
        await apiService.get('/group/info', params: {'groupId': groupId});
    await storeGroup(response['data']);
  }

  // 获取加入的群聊列表
  List<Group> getlocalGroupList() {
    return _groupRepository.getGroupList();
  }

  // 根据房间 ID 获取房间详情
  Group getLocalGroupById(String groupId) {
    final Group? group = _groupRepository.getGroup(groupId);
    if (group == null) throw Exception('群聊数据丢失，请尝试重新登录');
    return group;
  }

  // 修改房间信息
  Future<Map<String, dynamic>> updateGroup(
      {required String groupId,
      String? groupName,
      int? vertifyType,
      String? notice}) async {
    final response = await apiService.put('/group/update', {
      if (groupName != null) 'groupName': groupName,
      if (vertifyType != null) 'vertifyType': vertifyType,
      if (notice != null) 'notice': notice
    });
    return response;
  }

  // 修改群聊头像
  Future<Map<String, dynamic>> uploadAvatar(
      String groupId, XFile imageFile) async {
    MultipartFile? avatarFile;

    try {
      avatarFile = await ImagePickerHelper.convertXFileToMultipart(imageFile);
      final formData = FormData.fromMap({
        'groupId': groupId,
        if (avatarFile != null) 'avatar': avatarFile,
      });

      final response = await apiService.postFormData('/group/avatar', formData);
      return response;
    } catch (e) {
      print(e);
      rethrow;
    }
  }

  // 设置管理员权限
  Future<Map<String, dynamic>> setAdmin(
      {required String groupId,
      required List memberIds,
      required bool isAdmin}) async {
    final response = await apiService.put('/group/setAdmin',
        {'groupId': groupId, 'memberIds': memberIds, 'isAdmin': isAdmin});
    return response;
  }

  // 邀请用户加入房间
  Future<Map<String, dynamic>> inviteMember(
      {required String groupId, required List memberIds}) async {
    final response = await apiService
        .put('/group/invite', {'groupId': groupId, 'memberIds': memberIds});
    return response;
  }

  // 踢出用户
  Future<Map<String, dynamic>> kickMember(
      {required String groupId, required List memberIds}) async {
    final response = await apiService
        .put('/group/kick', {'groupId': groupId, 'memberIds': memberIds});

    return response;
  }

  // 用户退出房间
  Future<Map<String, dynamic>> leaveGroup(String groupId) async {
    final response = await apiService.put('/group/leave', {'groupId': groupId});
    return response;
  }

  // 转让群主
  Future<Map<String, dynamic>> transferOwner(
      String groupId, String newOwner) async {
    final response = await apiService
        .put('/group/transfer', {'groupId': groupId, 'newOwner': newOwner});
    return response;
  }

  // 解散房间
  Future<Map<String, dynamic>> dismissGroup(String groupId) async {
    final response =
        await apiService.post('/group/dismiss', {'groupId': groupId});
    return response;
  }

  /// 修改群聊会话Id
  Future updateCoversationId(String conversationId, String groupId) async {
    final Group? group = await getGroupSafe(groupId);
    if (group == null) throw Error();
    final newGroup = group.copyWith(conversationId: conversationId);
    await _groupRepository.setGroup(newGroup);
  }

  // 根据房间 ID 获取房间详情(保险版)
  Future<Group?> getGroupSafe(String groupId) async {
    Group? group = _groupRepository.getGroup(groupId);
    if (group == null) {
      await getRemoteGroupById(groupId);
      group = _groupRepository.getGroup(groupId);
    }
    return group;
  }
}
